<template>
  <!-- 页面容器 -->
  <div class="order-outbound-container">
    <!-- 页面标题 -->
    <el-page-header
      title="返回订单列表"
      content="订单出库"
      @back="handleBack"
      class="page-header"
    />

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card shadow="never" class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form" label-width="100px">
          <!-- 出库单编号搜索项 -->
          <el-form-item label="出库单编号">
            <el-input v-model="searchForm.outboundNumber" placeholder="请输入出库单编号" clearable @keyup.enter="handleSearch"
              class="search-input" />
          </el-form-item>

          <!-- 操作员搜索项 -->
          <el-form-item label="操作员">
            <el-input v-model="searchForm.operator" placeholder="请输入操作员" clearable @keyup.enter="handleSearch"
              class="search-input" />
          </el-form-item>

          <!-- 快递公司搜索项 -->
          <el-form-item label="快递公司">
            <el-input v-model="searchForm.expressCompany" placeholder="请输入快递公司" clearable @keyup.enter="handleSearch"
              class="search-input" />
          </el-form-item>

          <!-- 快递单号搜索项 -->
          <el-form-item label="快递单号">
            <el-input v-model="searchForm.expressNumber" placeholder="请输入快递单号" clearable @keyup.enter="handleSearch"
              class="search-input" />
          </el-form-item>

          <!-- 操作按钮组 -->
          <el-form-item class="button-group">
            <el-button type="primary" @click="handleSearch" class="search-button">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset" class="reset-button">
              <el-icon>
                <Refresh />
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>出库单列表</span>
          <el-button type="primary" @click="handleCreateOutbound">新建出库单</el-button>
        </div>
      </template>

      <!-- 出库单数据表格 -->
      <el-table border :data="outboundList" :show-overflow-tooltip="true" v-loading="loading" class="order-table">
        <!-- 出库单编号列 -->
        <el-table-column prop="outbound_number" label="出库单编号" width="150" />
        <!-- 出库日期列 -->
        <el-table-column prop="outbound_date" label="出库日期" width="110">
          <template #default="{ row }">
            {{ formatDate(row.outbound_date) }}
          </template>
        </el-table-column>
        <!-- 操作员列 -->
        <el-table-column prop="operator" label="操作员" width="120" />
        <!-- 快递公司列 -->
        <el-table-column prop="express_company" label="快递公司" width="120" />
        <!-- 快递单号列 -->
        <el-table-column prop="express_number" label="快递单号" width="150" />
        <!-- 关联订单数量列 -->
        <el-table-column label="关联订单数" width="100">
          <template #default="{ row }">
            {{ row.orders?.length || 0 }}
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewOutboundDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
          :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 30, 40, 100]"
          @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </el-card>

    <!-- 订单选择对话框 -->
    <el-dialog v-model="orderSelectDialogVisible" title="选择订单" width="800px" :close-on-click-modal="false">
      <!-- 订单搜索区域 -->
      <el-card shadow="never" class="search-card" style="margin-bottom: 15px;">
        <el-form :inline="true" :model="orderSearchForm" class="search-form" label-width="80px">
          <!-- 订单编号搜索项 -->
          <el-form-item label="订单编号">
            <el-input v-model="orderSearchForm.orderNumber" placeholder="请输入订单编号" clearable @keyup.enter="handleOrderSearch"
              class="search-input" />
          </el-form-item>

          <!-- 客户姓名搜索项 -->
          <el-form-item label="客户姓名">
            <el-input v-model="orderSearchForm.customerName" placeholder="请输入客户姓名" clearable @keyup.enter="handleOrderSearch"
              class="search-input" />
          </el-form-item>

          <!-- 订单状态搜索项 -->
          <el-form-item label="订单状态">
            <el-select v-model="orderSearchForm.status" placeholder="请选择订单状态" clearable class="search-select">
              <el-option label="待处理" value="1" />
              <el-option label="已确认" value="2" />
              <el-option label="已入库" value="3" />
              <el-option label="已出库" value="4" />
              <el-option label="已完成" value="5" />
            </el-select>
          </el-form-item>

          <!-- 操作按钮组 -->
          <el-form-item class="button-group">
            <el-button type="primary" @click="handleOrderSearch" class="search-button">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </el-button>
            <el-button @click="handleOrderReset" class="reset-button">
              <el-icon>
                <Refresh />
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 订单数据表格 -->
      <el-table border :data="orderList" :show-overflow-tooltip="true" v-loading="orderLoading" class="order-table"
        @selection-change="orderSelection = $event">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="order_number" label="订单编号" width="150" />
        <el-table-column prop="customer_name" label="客户姓名" width="120" />
        <el-table-column prop="baby_name" label="婴儿姓名" width="120" />
        <el-table-column prop="product_name" label="产品名称" width="150" />
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="total_amount" label="总金额" width="100" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.total_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 1" type="info">待处理</el-tag>
            <el-tag v-else-if="row.status === 2" type="primary">已确认</el-tag>
            <el-tag v-else-if="row.status === 3" type="success">已入库</el-tag>
            <el-tag v-else-if="row.status === 4" type="warning">已出库</el-tag>
            <el-tag v-else-if="row.status === 5" type="success">已完成</el-tag>
            <el-tag v-else>未知</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 订单分页组件 -->
      <div class="pagination-container">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="orderTotal"
          :current-page="orderCurrentPage" :page-size="orderPageSize" :page-sizes="[10, 20, 30, 40, 100]"
          @current-change="handleOrderPageChange" @size-change="handleOrderSizeChange" />
      </div>

      <!-- 对话框底部操作区域 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="orderSelectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmOrderSelection">
            确认选择
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 出库对话框 -->
    <el-dialog v-model="outboundDialogVisible" :title="outboundForm.order_ids && outboundForm.order_ids.length > 1 ? '批量订单出库' : '订单出库'" width="500px" :close-on-click-modal="false">
      <el-form ref="outboundFormRef" :model="outboundForm" :rules="outboundRules" label-width="100px" v-loading="saveLoading">
        <el-form-item label="订单编号" v-if="outboundForm.order_ids && outboundForm.order_ids.length === 1">
          <el-input v-model="outboundForm.order_numbers[0]" readonly />
        </el-form-item>
        <el-form-item label="订单编号" v-else-if="outboundForm.order_ids && outboundForm.order_ids.length > 1">
          <el-input :value="`${outboundForm.order_numbers.length} 个订单`" readonly />
          <div style="margin-top: 5px; max-height: 100px; overflow-y: auto;">
            <div v-for="(num, index) in outboundForm.order_numbers" :key="index" style="font-size: 12px; color: #666;">{{ num }}</div>
          </div>
        </el-form-item>
        <el-form-item label="出库日期" prop="outbound_date">
          <el-date-picker v-model="outboundForm.outbound_date" type="date" placeholder="请选择出库日期" style="width: 100%"
            value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
        </el-form-item>
        <el-form-item label="操作员" prop="operator">
          <el-input v-model="outboundForm.operator" placeholder="请输入操作员姓名" />
        </el-form-item>
        <el-form-item label="快递公司" prop="express_company">
          <el-input v-model="outboundForm.express_company" placeholder="请输入快递公司名称" />
        </el-form-item>
        <el-form-item label="快递单号" prop="express_number">
          <el-input v-model="outboundForm.express_number" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="outboundForm.notes" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outboundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveOutbound" :loading="saveLoading">
            确定出库
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 订单出库页面组件
 * 负责展示待出库订单列表和处理订单出库操作
 */
defineOptions({
  name: 'OrderOutboundView'
})

// 从Vue中导入所需的API
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

// 导入Element Plus组件和相关API
import { ElMessage } from 'element-plus'

// 导入图标组件
import { Search, Refresh } from '@element-plus/icons-vue'

// 导入订单相关的API函数
import { addOrderOutbound, getOrderOutboundList } from '@/api/OrderOutbounds'
import { getOrderList } from '@/api/SalesOrders'

// 获取路由实例
const router = useRouter()

// 响应式数据定义
const outboundList = ref([])        // 出库单列表数据
const orderList = ref([])           // 订单列表数据（用于选择）
const loading = ref(false)          // 列表加载状态
const orderLoading = ref(false)     // 订单列表加载状态
const saveLoading = ref(false)      // 保存按钮加载状态
const total = ref(0)                // 总数据条数
const orderTotal = ref(0)           // 订单总数据条数
const currentPage = ref(1)          // 当前页码
const orderCurrentPage = ref(1)     // 订单当前页码
const pageSize = ref(10)            // 每页条数
const orderPageSize = ref(10)       // 订单每页条数

// 搜索表单数据
const searchForm = ref({
  outboundNumber: '',   // 出库单编号搜索条件
  operator: '',         // 操作员搜索条件
  expressCompany: '',   // 快递公司搜索条件
  expressNumber: ''     // 快递单号搜索条件
})

// 出库对话框相关状态
const outboundDialogVisible = ref(false)    // 出库对话框显示状态
const orderSelectDialogVisible = ref(false) // 订单选择对话框显示状态
const outboundFormRef = ref(null)           // 出库表单引用
const outboundForm = ref({
  order_ids: [],
  order_numbers: [],
  outbound_date: new Date().toISOString().slice(0, 10),  // 默认为今天
  operator: '',
  express_company: '',
  express_number: '',
  notes: ''
})

// 订单选择对话框相关状态
const orderSelection = ref([])              // 订单选择的数据
const orderSearchForm = ref({
  orderNumber: '',     // 订单编号搜索条件
  customerName: '',    // 客户姓名搜索条件
  status: ''           // 订单状态搜索条件
})

// 出库表单验证规则
const outboundRules = {
  outbound_date: [
    { required: true, message: '请选择出库日期', trigger: 'change' }
  ],
  operator: [
    { required: true, message: '请输入操作员姓名', trigger: 'blur' }
  ]
}

/**
 * 禁用未来日期
 * @param {Date} date - 日期对象
 * @returns {boolean} 是否禁用该日期
 */
const disabledDate = (date) => {
  return date.getTime() > Date.now()
}

/**
 * 格式化日期显示
 * @param {string} date - 日期字符串
 * @returns {string} 格式化后的日期
 */
const formatDate = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

/**
 * 格式化金额显示
 * @param {any} amount - 金额值
 * @returns {string} 格式化后的金额
 */
const formatAmount = (amount) => {
  // 如果金额为空或无效，返回默认值
  if (amount === null || amount === undefined || amount === '') {
    return '0.00'
  }

  // 尝试转换为数字
  const num = parseFloat(amount)

  // 如果转换失败，返回默认值
  if (isNaN(num)) {
    return '0.00'
  }

  // 格式化为两位小数
  return num.toFixed(2)
}

/**
 * 获取出库单列表数据
 */
const getOrderListData = async () => {
  try {
    loading.value = true

    // 构建分页参数对象
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      // 添加搜索参数
      outboundNumber: searchForm.value.outboundNumber,
      operator: searchForm.value.operator,
      expressCompany: searchForm.value.expressCompany,
      expressNumber: searchForm.value.expressNumber
    }

    // 调用API获取出库单列表
    const res = await getOrderOutboundList(params)

    // 处理响应数据
    if (res.data && Array.isArray(res.data.outbounds)) {
      outboundList.value = res.data.outbounds
      total.value = res.data.pagination?.totalCount || 0
      currentPage.value = res.data.pagination?.currentPage || 1
      pageSize.value = res.data.pagination?.pageSize || 10
    } else {
      outboundList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取出库单列表失败，请稍后重试！')
    outboundList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/**
 * 页码改变事件处理函数
 * @param {number} page - 新的页码
 */
const handlePageChange = (page) => {
  currentPage.value = page
  getOrderListData()
}

/**
 * 每页条数改变事件处理函数
 * @param {number} size - 新的每页条数
 */
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getOrderListData()
}

/**
 * 搜索按钮点击事件处理函数
 */
const handleSearch = () => {
  currentPage.value = 1
  getOrderListData()
}

/**
 * 重置按钮点击事件处理函数
 */
const handleReset = () => {
  searchForm.value = {
    outboundNumber: '',
    operator: '',
    expressCompany: '',
    expressNumber: ''
  }
  currentPage.value = 1
  getOrderListData()
}

/**
 * 获取订单列表数据（用于选择）
 */
const getOrderListForSelection = async () => {
  try {
    orderLoading.value = true

    // 构建分页参数对象
    const params = {
      page: orderCurrentPage.value,
      pageSize: orderPageSize.value,
      // 添加搜索参数
      orderNumber: orderSearchForm.value.orderNumber,
      customerName: orderSearchForm.value.customerName,
      status: orderSearchForm.value.status
    }

    // 调用API获取订单列表
    const res = await getOrderList(params)

    // 处理响应数据
    if (res.data && Array.isArray(res.data.orders)) {
      orderList.value = res.data.orders
      orderTotal.value = res.data.pagination?.totalCount || 0
    } else {
      orderList.value = []
      orderTotal.value = 0
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败，请稍后重试！')
    orderList.value = []
    orderTotal.value = 0
  } finally {
    orderLoading.value = false
  }
}

/**
 * 订单页码改变事件处理函数
 * @param {number} page - 新的页码
 */
const handleOrderPageChange = (page) => {
  orderCurrentPage.value = page
  getOrderListForSelection()
}

/**
 * 订单每页条数改变事件处理函数
 * @param {number} size - 新的每页条数
 */
const handleOrderSizeChange = (size) => {
  orderPageSize.value = size
  orderCurrentPage.value = 1
  getOrderListForSelection()
}

/**
 * 订单搜索按钮点击事件处理函数
 */
const handleOrderSearch = () => {
  orderCurrentPage.value = 1
  getOrderListForSelection()
}

/**
 * 订单重置按钮点击事件处理函数
 */
const handleOrderReset = () => {
  orderSearchForm.value = {
    orderNumber: '',
    customerName: '',
    status: ''
  }
  orderCurrentPage.value = 1
  getOrderListForSelection()
}

/**
 * 确认选择订单
 */
const confirmOrderSelection = () => {
  if (orderSelection.value.length === 0) {
    ElMessage.warning('请至少选择一个订单')
    return
  }

  // 设置选中的订单信息到出库表单
  outboundForm.value.order_ids = orderSelection.value.map(item => item.order_id)
  outboundForm.value.order_numbers = orderSelection.value.map(item => item.order_number)

  // 关闭订单选择对话框
  orderSelectDialogVisible.value = false

  // 显示出库对话框
  outboundDialogVisible.value = true
}

/**
 * 返回订单列表
 */
const handleBack = () => {
  router.push('/orders')
}

/**
 * 查看出库单详情
 * @param {Object} row - 出库单数据行
 */
const viewOutboundDetail = (row) => {
  // 这里可以跳转到详情页面或者显示详情对话框
  console.log('查看出库单详情:', row)
  ElMessage.info('查看出库单详情功能待实现')
}

/**
 * 新建出库单
 */
const handleCreateOutbound = () => {
  // 重置表单数据
  outboundForm.value = {
    order_ids: [],
    order_numbers: [],
    outbound_date: new Date().toISOString().slice(0, 10),
    operator: '',
    express_company: '',
    express_number: '',
    notes: ''
  }

  // 重置订单搜索条件
  orderSearchForm.value = {
    orderNumber: '',
    customerName: '',
    status: ''
  }

  // 重置订单分页
  orderCurrentPage.value = 1

  // 加载订单数据
  getOrderListForSelection()

  // 显示订单选择对话框
  orderSelectDialogVisible.value = true
}

/**
 * 保存订单出库信息
 */
const handleSaveOutbound = async () => {
  // 表单验证
  try {
    await outboundFormRef.value.validate()
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.warning('请填写完整的出库信息')
    return
  }

  try {
    saveLoading.value = true

    // 准备提交数据
    const submitData = {
      order_ids: outboundForm.value.order_ids,
      outbound_date: outboundForm.value.outbound_date,
      operator: outboundForm.value.operator,
      express_company: outboundForm.value.express_company,
      express_number: outboundForm.value.express_number,
      notes: outboundForm.value.notes
    }

    // 创建出库记录
    await addOrderOutbound(submitData)
    ElMessage.success('订单出库成功！')

    // 关闭对话框
    outboundDialogVisible.value = false

    // 重新加载列表数据
    getOrderListData()
  } catch (error) {
    console.error('订单出库失败:', error)
    ElMessage.error(`订单出库失败：${error.msg || error.message || '请稍后重试！'}`)
  } finally {
    saveLoading.value = false
  }
}

// 组件挂载时获取订单列表数据
onMounted(() => {
  getOrderListData()
})

</script>

<style scoped>
/**
 * 订单出库页面样式部分
 * 使用scoped属性确保样式只作用于当前组件
 */

/* 页面容器样式 */
.order-outbound-container {
  padding: 20px;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 20px;
}

/* 搜索容器样式 */
.search-container {
  margin-bottom: 20px;
}

/* 搜索卡片样式 */
.search-card {
  border: 1px solid #e4e7ed;
}

/* 搜索表单样式 */
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 0;
}

/* 搜索表单项样式 */
.search-form .el-form-item {
  margin-bottom: 0;
  flex: 0 0 auto;
}

/* 搜索输入框样式 */
.search-input {
  width: 150px;
}

/* 搜索选择框样式 */
.search-select {
  width: 150px;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-left: auto !important;
}

/* 搜索按钮样式 */
.search-button {
  white-space: nowrap;
}

/* 重置按钮样式 */
.reset-button {
  white-space: nowrap;
}

/* 表格卡片样式 */
.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格头部样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

/* 表格头部标题样式 */
.table-header span {
  font-size: 16px;
  font-weight: bold;
}

/* 订单数据表格 */
.order-table {
  width: 100%;
}

/* 分页容器样式 */
.pagination-container {
  text-align: right;
  margin-top: 20px;
}

/* 价格列样式 */
.price-column {
  text-align: right;
}

/* 对话框底部操作区域样式 */
.dialog-footer {
  text-align: right;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    width: 100%;
  }

  .search-input,
  .search-select {
    width: 100%;
  }

  .button-group {
    margin-left: 0 !important;
    width: 100%;
    justify-content: center;
  }

  .table-header {
    flex-direction: column;
    align-items: stretch;
  }

  .table-header>div {
    justify-content: center;
  }
}
</style>
